<script lang="ts" setup>
import type { OrgModel } from '#/api/system/models';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm, z } from '#/adapter/form';
import { createOrgApi, getOrgListApi, updateOrgApi } from '#/api/system/org';
import { toTree } from '#/utils/tree';

defineOptions({
  name: 'OrgFormModal',
});

const emit = defineEmits<{
  complete: [];
}>();

async function onSubmit(values: Record<string, any>) {
  const input = values as OrgModel;
  await (input.id ? updateOrgApi(input) : createOrgApi(input));
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        triggerFields: ['code'],
        disabled(values) {
          return !!values.id;
        },
      },
      fieldName: 'code',
      label: '部门代码',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'name',
      label: '部门名称',
      rules: 'required',
    },
    {
      component: 'TreeSelect',
      componentProps: {
        allowClear: true,
        treeNodeFilterProp: 'label',
        treeData: [],
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        treeLine: true,
      },
      fieldName: 'parentId',
      label: '上级部门',
    },
    {
      component: 'InputNumber',
      fieldName: 'order',
      label: '排序',
      defaultValue: 100,
      rules: z.number().gte(0),
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '禁用',
        class: 'w-auto',
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
    },
    {
      component: 'Textarea',
      componentProps: {
        showCount: true,
        maxlength: 128,
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (await formApi.validateAndSubmitForm()) {
      modalApi.close();
      emit('complete');
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { values } = modalApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values, false);
        modalApi.setState({ title: '编辑部门' });
      }

      // 设置部门列表
      const resp = await getOrgListApi();
      formApi.updateSchema([
        {
          componentProps: {
            treeData: toTree(resp),
          },
          fieldName: 'parentId',
        },
      ]);
    }
  },
  title: '新增部门',
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
